﻿namespace sfcms.api
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Web;

    public class urlrewriter : IHttpModule
    {
        private static Dictionary<string, string> urlcache = new Dictionary<string, string>();

        private void context_BeginRequest(object sender, EventArgs e)
        {
            string requestedUrl = toasciilower(HttpContext.Current.Request.Url.AbsolutePath);
            if (urlcache.ContainsKey(requestedUrl))
            {
                HttpContext.Current.RewritePath(urlcache[requestedUrl]);
            }
            else
            {
                string[] requestedUrlPath = requestedUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                folder f = folder.pageroot;
                for (int i = 0; i < (requestedUrlPath.Length - 1); i++)
                {
                    f = folder.byparentidanddisplayname(folder.pageroot.type, f.id, requestedUrlPath[i]);
                    if (f == null)
                    {
                        return;
                    }
                }
                page p = page.byparentidanddisplayname(f.id, Path.GetFileNameWithoutExtension(requestedUrlPath[requestedUrlPath.Length - 1]));
                if (p != null)
                {
                    urlcache.Add(requestedUrl, p.templatepath + "?sfcms=" + p.id);
                    HttpContext.Current.RewritePath(urlcache[requestedUrl]);
                }
            }
        }

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(this.context_BeginRequest);
        }

        public static string toasciilower(string fullstring)
        {
            char[] chars = fullstring.ToLower().ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                char replacement = chars[i];
                switch (chars[i])
                {
                    case 'ğ':
                        replacement = 'g';
                        break;

                    case 'ı':
                        replacement = 'i';
                        break;

                    case 'ş':
                        replacement = 's';
                        break;

                    case '\x00e7':
                        replacement = 'c';
                        break;

                    case '\x00f6':
                        replacement = 'o';
                        break;

                    case '\x00fc':
                        replacement = 'u';
                        break;
                }
                chars[i] = replacement;
            }
            return new string(chars).Replace(" ", "");
        }
    }
}

